< previous page page_172 next page >

Page 172
To convert a pixel's color into a grayscale value, set the pixel's red, green, and blue color components to the average of the three values.
Example program MakeGray uses the TransformImage subroutine shown in the following code to convert the image in picture box picOriginal into a grayscale image displayed in picResult. It uses the GetBitmapPixels subroutine to load the input picture's pixel information. It examines each pixel and sets its color components to the average of the pixel's components. It then uses the SetBitmapPixels subroutine to copy the resulting pixel values into the picResult picture box. Subroutines GetBitmapPixels and SetBitmapPixels are described in Chapter 3.
e10a6a0a59f035e870d90cca05b85fce.gif
' Transform the image.
Private Sub TransformImage()
Dim pixels() As RGBTriplet
Dim bits_per_pixel As Integer
Dim X As Integer
Dim Y As Integer
Dim shade As Integer

    ' Get the pixels from picOriginal. 
    GetBitmapPixels picOriginal, pixels, bits_per_pixel 

    ' Set the pixel colors. 
    For Y = 0 To picOriginal.ScaleHeight - 1 
        For X = 0 To picOriginal.ScaleWidth - 1 
            With pixels(X, Y) 
                 shade = (CInt(.rgbRed) + .rgbGreen + _
                     .rgbBlue) / 3
                 .rgbRed = shade
                 .rgbGreen = shade
                 .rgbBlue = shade
             End With
        Next X
    Next Y

    ' Set picResult's pixels. 
    SetBitmapPixels picResult, bits_per_pixel, pixels 
    picResult.Picture = picResult.Image 
End Sub
All the code specific to the grayscale transformation is contained in subroutine TransformImage. That lets you modify the program to create other point process transformations quickly and easily. In most cases, you will need to change only the four statements that calculate and set the pixels' new values. Several of the other examples in this chapter use this approach and differ from program MakeGray only in these four statements.
When you work with program MakeGray, you will notice that the program quickly loads the image file you select. It then takes a while to create the grayscale version. In one test on a 133MHz Pentium processor, the program loaded a 720 by 486 pixel image almost

 
< previous page page_172 next page >